package com.atguigu.yygh.hosp.service.impl;



import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    //保存排班
    @Override
    public void save(Map<String, Object> paramMap) {
        //paramMap 转换department对象
        String schJsonStr = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(schJsonStr, Schedule.class);
        //根据医院编码 排班编号（医院自己编号）查询排班信息
        Schedule scheduleExist =
                scheduleRepository.getByHoscodeAndHosScheduleId(
                        schedule.getHoscode(),schedule.getHosScheduleId()
                );
        //判断更新新增
        if (scheduleExist != null){
            //更新
            schedule.setId(scheduleExist.getId());
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else {
            //新增
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
            .withIgnoreCase(true);//改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Schedule> example = Example.of(schedule,matcher);
        Page<Schedule> pages = scheduleRepository.findAll(example,pageable);

        return pages;
    }
    //删除排班
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getByHoscodeAndHosScheduleId(hoscode,hosScheduleId);
        if (schedule != null){
            scheduleRepository.deleteById(schedule.getId());
        }
    }
    //根据医院编号 和 科室编号 ，查询排班规则数据
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //0创建返回数据
        Map<String, Object> result = new HashMap<>();
        //1根据查询条件、分页查询统计规则数据（获取list）
        //1.1设置查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode);
        //1.2分组统计（聚合统计）
        Aggregation agg = Aggregation.newAggregation(
                //1.3匹配筛选条件
                Aggregation.match(criteria),
                //1.4分组字段
                Aggregation.group("workDate")
                        //1.5分组统计结果
                        .first("workDate").as("workDate")
                        //统计医生数量
                        .count().as("docCount")
                        //统计号源信息
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //1.6 排序
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                //1.7分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)

        );
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();

        //2根据查询条件查询统计规则数据（获取total）
        Aggregation totalAgg = Aggregation.newAggregation(
                //2.1匹配筛选条件
                Aggregation.match(criteria),
                //2.1分组字段
                Aggregation.group("workDate")
        );
        //2.3调方法查询
        AggregationResults<BookingScheduleRuleVo> aggregateTotal = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleTotal = aggregateTotal.getMappedResults();
        int total = bookingScheduleRuleTotal.size();
        //3借助工具算出周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //4封装数据
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);
        //5数据补全
        //5.1获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);

        return result;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        //1根据医院编号 、科室编号和工作日期，查询排班记录
        //转化WorkDate类型，String->Date
        Date workDateToDate = new DateTime(workDate).toDate();
        List<Schedule> scheduleList =
                scheduleRepository.getByHoscodeAndDepcodeAndWorkDate(
                        hoscode,depcode,workDateToDate);

        //2根据编码查询具体名称用于展示
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });

        return scheduleList;
    }
    //获取可预约排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result  = new HashMap<>();
        //1根据hoscode查询医院信息，获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if(hospital==null){
            throw new YyghException(20001,"医院信息有误");
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //2根据预约规则，统计带分页的可预约的日期集合IPage<Date>
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);
        List<Date> dateList = iPage.getRecords();

        //3 参考后台接口方法，查询聚合的排班信息
        //3.1准备查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        //3.2创建聚合对象
        Aggregation agg  = Aggregation.newAggregation(//创建聚合对象
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组聚合字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber")
        );
        //3.3通过mongoTemplate查询数据
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleList = aggregate.getMappedResults();
        //3.4 把scheduleList转化成map k:workDate v:BookingScheduleRuleVo
        Map<Date,BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleList)){
            scheduleVoMap = scheduleList.stream().collect(Collectors.toMap(
                    BookingScheduleRuleVo::getWorkDate,
                    BookingScheduleRuleVo->BookingScheduleRuleVo
            ));
        }
        //4整合两部分数据，（1）可预约的日期集合dateList (2)聚合的排班信息scheduleVoMap
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0,let = dateList.size() ; i <let ; i++) {
            //4.1取出每一个可预约的日期
            Date date = dateList.get(i);
            //4.2根据date取出BookingScheduleRuleVo
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //4.3 如果date当天没有数据，进行初始化
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //4.4判断周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            //4.5最后一页最后一条记录为即将预约 状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i==let-1&& page==iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else{
                bookingScheduleRuleVo.setStatus(0);
            }
            //4.6当天预约如果过了停号时间，不能预约（-1：当天已停止挂号）
            if(i==0 && page==1){
                //当天停号时间
                DateTime stopTime = this.getDateTime(new Date(),bookingRule.getStopTime());
                if(stopTime.isBeforeNow()){
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //5封装数据到map里，返回
        result.put("bookingScheduleList",bookingScheduleRuleVoList);
        result.put("total",iPage.getTotal());

        //其他基础数据
        Map<String,Object> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);

        return result;
    }
    //根据排班id获取排班详情
    @Override
    public Schedule findScheduleById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        return this.packageSchedule(schedule);
    }
    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //1、根据排班id获取排班详情
        Schedule schedule = this.findScheduleById(scheduleId);
        if (schedule == null){
            throw new YyghException(20001,"排班信息有误");
        }
        //2、根据hoscode获取医院相关信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(20001, "预约规则信息有误");
        }
        //3、
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null) {
            throw new YyghException(20001, "预约规则信息有误");
        }
        //4、数据封装
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(stopTime.toDate());
        return scheduleOrderVo;
    }
    //修改排班
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    //根据医院编码，医院排班id查询排班
    @Override
    public Schedule getScheduleByIds(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        return schedule;
    }

    //获取可预约日期的分页数据
    private IPage<Date> getListDate(int page, int limit,
                                    BookingRule bookingRule){
        //1获取当前的预约时间，当前日期+预约放号时间
        DateTime releaseTime = this.getDateTime(new Date(),bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //判断当前预约时间是否小于系统时间，如果是，给预约周期+1
        if(releaseTime.isBeforeNow()) cycle+=1;
        //2获取满足预约周期的日期集合
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i <cycle ; i++) {
            DateTime plusDays = new DateTime().plusDays(i);
            String dateString = plusDays.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //3 获取分页信息，默认每页7条
        int start = (page-1)*limit;
        int end = (page-1)*limit +limit;
        if(end>dateList.size()) end = dateList.size();
        //4 获取分页后的日期集合
        List<Date> datePageList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            datePageList.add(dateList.get(i));
        }
        //5封装配置对象
        IPage<Date> datePage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,limit,dateList.size());
        datePage.setRecords(datePageList);
        return datePage;
    }
    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString =
                new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    private Schedule packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",
                hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
